package com.huijz.flywaydemo.callback;

import org.flywaydb.core.api.callback.Callback;
import org.flywaydb.core.api.callback.Context;
import org.flywaydb.core.api.callback.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 演示：Flyway回调
 * 可以在迁移的不同阶段执行自定义逻辑
 */
@Component
public class FlywayCallbackDemo implements Callback {
    
    private static final Logger logger = LoggerFactory.getLogger(FlywayCallbackDemo.class);

    @Override
    public boolean supports(Event event, Context context) {
        // 支持所有事件
        return true;
    }

    @Override
    public boolean canHandleInTransaction(Event event, Context context) {
        // 所有事件都在事务中处理
        return true;
    }

    @Override
    public void handle(Event event, Context context) {
        switch (event) {
            case BEFORE_MIGRATE:
                logger.info("迁移开始前的回调");
                break;
            case AFTER_MIGRATE:
                logger.info("迁移完成后的回调");
                break;
            case BEFORE_EACH_MIGRATE:
                logger.info("每个迁移脚本执行前的回调: {}", context.getMigrationInfo().getDescription());
                break;
            case AFTER_EACH_MIGRATE:
                logger.info("每个迁移脚本执行后的回调: {}", context.getMigrationInfo().getDescription());
                break;
            case AFTER_VALIDATE:
                logger.info("验证完成后的回调");
                break;
            default:
                logger.info("其他Flyway事件: {}", event);
        }
    }

    @Override
    public String getCallbackName() {
        String name = this.getClass().getSimpleName();
        if (name.contains("__")) {
            name = name.split("__")[1];
        }

        return name;
    }
}